package com.project.controller.home;

import com.alibaba.fastjson.JSON;
import com.project.controller.base.BaseController;
import com.project.model.Category;
import com.project.model.Topics;
import com.project.service.CategoryService;
import com.project.service.TopicsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("topics")
public class TopicsController extends BaseController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    TopicsService topicsService;

    @GetMapping("create")
    public String create(Model model) {
        model.addAttribute("id",0);
        return "home/topics/createAndEdit";
    }
    @ResponseBody
    @PostMapping("create")
    public String doCreate(Topics topics) {
        Map<String,Object> map = new HashMap<>();
        int res = topicsService.create(topics);
        if (res > 0) {
            map.put("status",true);
        } else {
            map.put("status",false);
            map.put("content","网络异常，请稍后再试");
        }
        return JSON.toJSONString(map);
    }
    @GetMapping("edit/{id}")
    public String edit(@PathVariable("id") int id, Model model) {
        model.addAttribute("id",id);
        return "home/topics/createAndEdit";
    }
    @ResponseBody
    @PostMapping("getCategory")
    public String getCategory() {
        List<Category> category = categoryService.selectAllCategory();
        return JSON.toJSONString(category);
    }
    @ResponseBody
    @PostMapping("getEditInfo")
    public String getEditInfo(@RequestParam("id") int id) {
        return topicsService.getEditInfo(id);
    }
}
